<script setup lang="ts">
import { reactive, ref, toRaw } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useQuery } from "@/hooks/init";
import { useShare } from "@/hooks/share";
import {
  buy_info_api,
  buy_info_select_day_api,
} from "@/package/mall/api/tour_product";
import { add_cancel_favorite_api } from "@/api/favorite";
import { data_api } from "@/api/my";
import { previewImage } from "@/utils/meida";
import { Account } from "@/utils/account";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import Swipe from "@/components/swipe/swipe.vue";
import DetailDateItem from "./components/detail-date-item.vue";
import DetailDateMore from "./components/detail-date-more.vue";
import DetailCommentEmpty from "../goods/components/detail-comment-empty.vue";
import DetailCommentScore from "../goods/components/detail-comment-score.vue";
import DetailMoreBtn from "../goods/components/detail-more-btn.vue";
import DetailCommentItem from "../goods/components/detail-comment-item.vue";
import DetailConsultItem from "./components/detail-consult-item.vue";
import DetailMenuBtn from "../goods/components/detail-menu-btn.vue";
import ServiceContact from "@/components/service/contact.vue";
import FormButton from "@/components/form/button.vue";

onLoad((options) => {
  useQuery<{ id: string; guiderId?: string }>(
    options as MiniApp.AppLaunchOption,
    (query) => {
      buy_info_api({ product_id: query.id }).then((resp) => {
        uni.setNavigationBarTitle({ title: resp.product_name });

        adList.value = (resp.pic_list as string[]).map((i) => {
          return { type: "img", url: i };
        });
        if (resp.video_url) {
          adList.value.unshift({
            type: "video",
            url: resp.video_url,
            poster: resp.pic_list[0],
          });
        }
        infoData.min_price = resp.min_price;
        infoData.max_price = resp.max_price;
        infoData.product_name = resp.product_name;
        infoData.product_subtitle = resp.product_subtitle;
        infoData.tag = resp.tag;
        infoData.sold_count = resp.sold_count;
        infoData.comment_score = Number(resp.comment.score);
        infoData.comment_count = resp.comment.count;
        infoData.comment_list = resp.comment.list;
        infoData.consult_count = resp.consult.count;
        // infoData.consult_items = resp.consult.items;
        infoData.info_text = resp.info_text.replace(
          /\<img/gi,
          '<img class="detail-intro-img" '
        );
        const extend_tips = resp.extend_tips;
        if (resp.travel_tips) {
          extend_tips.unshift({
            name: "游玩须知",
            value: resp.travel_tips,
          });
        }
        if (resp.traffic_line && resp.traffic_line.length !== 0) {
          extend_tips.unshift({
            name: "交通指引",
            value: resp.traffic_line
              .map((i: any) => `${i.name}：${i.content}`)
              .join("\n\n"),
          });
        }
        infoData.extend_tips = extend_tips;

        shareOption.title = resp.product_name;
        shareOption.imageUrl = resp.pic_list[0];
      });

      buy_info_select_day_api({ product_id: query.id }).then((resp) => {
        infoData.select_day = resp.select_day;
      });

      tempData.id = query.id;
      Account.isLogin && reloadMyData();

      shareOption.data = { id: query.id };

      tempData.guiderId = query.guiderId || "";
    }
  );
});

const adIndex = ref(0);
const adList = ref<any[]>([]);
const adClick = () => {
  const _adList = toRaw(adList.value);
  const _adIndex = toRaw(adIndex.value);
  if (_adList[_adIndex].type === "video") {
  } else {
    // 第一个是否是视频
    if (_adList[0].type === "video") {
      previewImage(
        _adList.filter((i) => i.type === "img").map((i) => i.url),
        _adIndex - 1
      );
    } else {
      previewImage(
        _adList.map((i) => i.url),
        _adIndex
      );
    }
  }
};

const infoData = reactive({
  min_price: "",
  max_price: "",
  product_name: "",
  product_subtitle: "",
  tag: "",
  sold_count: "",
  select_day: [] as any[],
  comment_score: 5,
  comment_count: 0,
  comment_list: [] as any[],
  consult_count: 0,
  consult_items: [] as any[],
  info_text: "",
  extend_tips: [] as any[],
  recommend_product: [] as any[],
});

const dateClick = (index: number) => {
  const date = infoData.select_day[index];
  if (date.status === 0) return Toast.show("该日期不可约");
  else if (date.status === 3) return Toast.show("该日期已约满");

  buyClick(date.date);
};

const commentClick = () => {
  Router.navigateTo(`/package/mall/pages/jps/comment?id=${tempData.id}`);
};

const consultClick = () => {
  Router.navigateTo(`/package/mall/pages/jps/consult?id=${tempData.id}`);
};

const buyClick = (date: string) => {
  Router.navigateTo(
    `/package/mall/pages/jps/package?${Router.dataToQuery({
      id: tempData.id,
      name: infoData.product_name,
      date,
      guiderId: tempData.guiderId,
    })}`
  );
};

const myData = reactive({ isCollect: false });
const collectClick = () => {
  const fn = () => {
    myData.isCollect = !myData.isCollect;
    add_cancel_favorite_api({
      favId: tempData.id,
      type: 50,
      status: myData.isCollect ? 1 : 2,
    });
  };
  Account.isLogin
    ? fn()
    : Account.login(() => {
        reloadMyData().then(() => {
          // 没有收藏，则收藏
          myData.isCollect || fn();
        });
      });
};

const reloadMyData = () => {
  return data_api<{ tour_product_favorite?: number[] }>({
    includes: "tour_product_favorite",
  }).then((resp) => {
    const id = Number(tempData.id);
    myData.isCollect = !!resp.tour_product_favorite?.includes(id);
  });
};

const tempData = { id: "", guiderId: "" };

const { onShareAppMessage, onShareTimeline, shareOption } = useShare(
  "/package/mall/pages/jps/detail"
);
</script>

<template>
  <view class="detail-ad" @click="adClick">
    <Swipe v-model="adIndex" :listData="adList" />

    <img
      class="detail-collect"
      :src="
        myData.isCollect
          ? '/package/mall/static/goods-detail-collect2.png'
          : '/package/mall/static/goods-detail-collect.png'
      "
      @click.stop="collectClick"
    />
  </view>

  <view class="detail-info">
    <view class="detail-info-price">
      <text class="detail-info-price2">￥</text
      >{{
        infoData.min_price === infoData.max_price
          ? infoData.min_price
          : `${infoData.min_price}-${infoData.max_price}`
      }}
    </view>
    <view class="detail-info-name">{{ infoData.product_name }}</view>
    <view class="detail-info-desc">{{ infoData.product_subtitle }}</view>
    <view style="display: flex; align-items: center">
      <view class="detail-info-tag">{{ infoData.tag }}</view>
      <view class="detail-info-sale">{{ infoData.sold_count }}</view>
    </view>
  </view>

  <view class="detail-date">
    <view class="detail-date-title">选择套餐·日期</view>
    <view class="detail-date-wrapper">
      <view
        class="detail-date-item"
        v-for="(i, d) of infoData.select_day"
        :key="i.date"
        @click="dateClick(d)"
      >
        <DetailDateItem :info="i" />
      </view>
      <view class="detail-date-more" @click="buyClick('')">
        <DetailDateMore />
      </view>
    </view>
  </view>

  <view class="detail-comment">
    <view class="detail-comment-title">评价</view>
    <view
      class="detail-comment-empty"
      v-if="infoData.comment_list.length === 0"
    >
      <DetailCommentEmpty />
    </view>
    <template v-else>
      <view class="detail-comment-score" v-if="infoData.comment_score > 0">
        <DetailCommentScore :modelValue="infoData.comment_score" />
      </view>
      <view class="detail-comment-all" @click="commentClick">
        <DetailMoreBtn :text="`${infoData.comment_count}条评论`" />
      </view>
      <view class="detail-comment-wrapper">
        <view
          class="detail-comment-item"
          v-for="i of infoData.comment_list"
          :key="i.id"
        >
          <DetailCommentItem :info="i" />
        </view>
      </view>
    </template>
  </view>

  <view class="detail-consult">
    <view class="detail-consult-title">
      咨询（{{ infoData.consult_count }}）
    </view>
    <view
      class="detail-consult-empty"
      v-if="infoData.consult_items.length === 0"
    >
      对行程有疑问？请咨询商家。
      <div class="detail-consult-btn" @click="consultClick">问问商家</div>
    </view>
    <template v-else>
      <view class="detail-consult-all" @click="consultClick">
        <DetailMoreBtn text="查看全部" />
      </view>
      <view class="detail-consult-wrapper">
        <view
          class="detail-consult-item"
          v-for="i of infoData.consult_items"
          :key="i.id"
        >
          <DetailConsultItem :info="i" />
        </view>
      </view>
    </template>
  </view>

  <view class="detail-intro">
    <view class="detail-intro-title">产品详情</view>
    <view class="detail-intro-html">
      <rich-text :nodes="infoData.info_text" />
    </view>
  </view>

  <view class="detail-other" v-if="infoData.extend_tips.length !== 0">
    <view
      class="detail-other-item"
      v-for="i of infoData.extend_tips"
      :key="i.name"
    >
      <view class="detail-other-title">{{ i.name }}</view>
      <view class="detail-other-content">{{ i.value }}</view>
    </view>
  </view>

  <view class="detail-fixed">
    <view class="detail-fixed-menu">
      <DetailMenuBtn
        icon="/package/mall/static/goods-contact.png"
        text="咨询"
      />
      <ServiceContact />
    </view>
    <view class="detail-fixed-btn" @click="buyClick('')">
      <FormButton>立即购买</FormButton>
    </view>
  </view>
</template>

<style lang="scss">
page {
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.detail-ad {
  position: relative;
  height: 750rpx;
}

.detail-collect {
  position: absolute;
  top: 40rpx;
  right: 40rpx;
  width: 64rpx;
  height: 64rpx;
}

.detail-info {
  padding: 24rpx 30rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-info-price {
    margin-bottom: 10rpx;
    font-size: 48rpx;
    color: #fa6400;
    line-height: 66rpx;
    font-weight: bold;
  }

  .detail-info-price2 {
    font-size: 32rpx;
    line-height: 44rpx;
  }

  .detail-info-name {
    margin-bottom: 26rpx;
    font-size: 36rpx;
    color: #333333;
    line-height: 50rpx;
    font-weight: bold;
  }

  .detail-info-desc {
    margin-bottom: 14rpx;
    font-size: 28rpx;
    color: #666666;
    line-height: 42rpx;
  }

  .detail-info-tag {
    padding: 0 14rpx;
    margin-right: 20rpx;
    font-size: 24rpx;
    color: #4e9b93;
    line-height: 42rpx;
    border-radius: 8rpx;
    border: 2rpx solid rgba(78, 155, 147, 0.2);
  }

  .detail-info-sale {
    flex-shrink: 0;
    margin-left: auto;
    font-size: 24rpx;
    color: #999999;
  }
}

.detail-date {
  padding: 40rpx 30rpx 20rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-date-title {
    margin-bottom: 40rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 48rpx;
    font-weight: bold;
  }

  .detail-date-wrapper {
    display: flex;
    align-items: center;
  }

  .detail-date-item,
  .detail-date-more {
    border-radius: 10rpx;
    border: 2rpx solid #eeeeee;
  }

  .detail-date-item {
    flex-grow: 1;
    width: 33.33%;
    margin-right: 12rpx;
  }

  .detail-date-more {
    flex-shrink: 0;
    width: 94rpx;
    height: 88rpx;
  }
}

.detail-comment {
  position: relative;
  padding: 40rpx 30rpx 30rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-comment-title {
    margin-bottom: 40rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 48rpx;
    font-weight: bold;
  }

  .detail-comment-score {
    position: absolute;
    left: 110rpx;
    top: 28rpx;
  }

  .detail-comment-all {
    position: absolute;
    top: 38rpx;
    right: 30rpx;
  }

  .detail-comment-empty {
    padding-bottom: 20px;
  }
}

.detail-consult {
  position: relative;
  padding: 40rpx 30rpx 20rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-consult-title {
    margin-bottom: 30rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 48rpx;
    font-weight: bold;
  }

  .detail-consult-all {
    position: absolute;
    top: 38rpx;
    right: 30rpx;
  }

  .detail-consult-empty {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #999999;
    line-height: 42rpx;
  }

  .detail-consult-btn {
    width: 256rpx;
    margin-left: auto;
    font-size: 28rpx;
    color: #ff7900;
    line-height: 56rpx;
    text-align: center;
    border-radius: 30rpx;
    border: 2rpx solid #ff7900;
  }
}

.detail-intro {
  padding: 40rpx 30rpx 30rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;

  .detail-intro-title {
    margin-bottom: 30rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 48rpx;
    font-weight: bold;
  }

  .detail-intro-html {
    color: #666666;
    overflow: hidden;
  }

  .detail-intro-img {
    width: 100%;
  }
}

.detail-other {
  margin-bottom: 40rpx;
  background-color: #ffffff;

  .detail-other-item {
    padding: 40rpx 30rpx 20rpx;
  }

  .detail-other-title {
    margin-bottom: 40rpx;
    font-size: 32rpx;
    color: #333333;
    line-height: 48rpx;
    font-weight: bold;
  }

  .detail-other-content {
    font-size: 26rpx;
    color: #666666;
    line-height: 44rpx;
    white-space: pre-line;
  }
}

.detail-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  height: 120rpx;
  padding-left: 30rpx;
  padding-right: 30rpx;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #ffffff;

  .detail-fixed-menu {
    position: relative;
    flex-shrink: 0;
  }

  .detail-fixed-btn {
    flex-grow: 1;
    min-width: 0;
    margin-left: 30rpx;
  }
}
</style>